import { EventBase } from "./EventBase";
import { CameraController } from "./CameraController";


const { ccclass, property } = cc._decorator;

@ccclass
export default class UITouchScript extends EventBase {
    horizontal: boolean = false;
    vertical: boolean = false;
    isDoubleFingerZoomIn: boolean = false;
    lastDoubleFingerDist: number = null;
    doubleFingerDist: number = null;
    touches: Array<cc.Event.EventTouch> = [];
    lastPoint: cc.Vec2 = cc.v2();
    isMoved: boolean = false;


    // 获取ui相机的触摸脚本
    static getUICameraTouchScript(): UITouchScript {
        UITouchScript.initUICamera();
        let ui = cc.find('Canvas/ui');
        return ui.getComponent(UITouchScript)
    }

    // 初始化UI相机事件
    static initUICamera() {
        let uiCamera,
            uiCameraComp,
            mainCamera = cc.find('Canvas/Main Camera'),
            ui = cc.find('Canvas/ui');
        // UI节点
        if (!ui) {
            ui = new cc.Node('ui');
            ui.parent = cc.find('Canvas');
        }
        ui.group = 'ui';
        ui.setContentSize(cc.winSize);
        // UI摄像机
        uiCamera = cc.find('Canvas/ui/UICamera')
        if (!uiCamera) {
            uiCamera = new cc.Node('UICamera');
            uiCamera.parent = ui;
            uiCamera.addComponent(cc.Camera)
        }
        uiCameraComp = uiCamera.getComponent(cc.Camera)
        uiCameraComp.cullingMask = 1 << 1;
        // 主摄像机
        if (mainCamera && mainCamera.isValid) {
            let mainCameraComp = mainCamera.getComponent(cc.Camera)
            mainCameraComp.cullingMask =
                ~(1 << 1)
                & ~(1 << 2)
                & ~(1 << 17);
        }
        // UI触摸移动相机事件
        if (!ui.getComponent(UITouchScript)) {
            ui.addComponent(UITouchScript);
        }
    }
    // 通过触摸ui节点移动相机
    private _isMoveByUI: boolean = false;
    get isMoveByUI(): boolean {
        return this._isMoveByUI;
    }
    set isMoveByUI(v: boolean) {
        this._isMoveByUI = v;
        // 获取脚本前会先初始化一遍
        let uiTouchScript = UITouchScript.getUICameraTouchScript();
        if (!!v) {
            uiTouchScript.registerEvent();
        } else {
            uiTouchScript.cancelEvent();
        }
    }
    limitRect: cc.Rect = null;
    // 更新UI相机参数
    updateUITouchState(limitRect: cc.Rect = null, horizontal: boolean, vertical: boolean) {
        if (limitRect) {
            // 设置相机的限制包围盒
            this.limitRect = limitRect;
        }
        // 是否通过触摸UI节点移动相机（水平、竖直）
        let uiTouchScript: UITouchScript = UITouchScript.getUICameraTouchScript();
        uiTouchScript.horizontal = horizontal;
        uiTouchScript.vertical = vertical;
        this.isMoveByUI = true;
    }

    onLoad() {
        super.onLoad && super.onLoad();
        this.buttonEffect = false;
    }

    private getDoubleFingerDist(touches: Array<cc.Event.EventTouch>): number {
        let res = null
        if (touches.length == 2) {
            res = touches[0].getLocation().sub(touches[1].getLocation()).mag();
        }
        return res;
    }

    zoomIn(touches: Array<cc.Event.EventTouch>) {
        this.doubleFingerDist = this.getDoubleFingerDist(touches);
        let camera = CameraController.instance;
        if (typeof this.lastDoubleFingerDist == "number" && typeof this.doubleFingerDist == "number") {
            camera.setCameraRatio(camera.cameraRatio + (this.doubleFingerDist - this.lastDoubleFingerDist) * 0.001)
            // GameHelper.showDebugInfoByLabel(`
            //     双指：${this.touches.length}
            //     上次距离：${this.lastDoubleFingerDist}
            //     本次距离：${this.doubleFingerDist}
            //     差距：${(this.doubleFingerDist - this.lastDoubleFingerDist)}
            //     实际相机增加率：${(this.doubleFingerDist - this.lastDoubleFingerDist) * 0.01}
            //     相机放大率${camera.cameraRatio}
            // `)
        }
        this.lastDoubleFingerDist = this.doubleFingerDist;
    }

    touchStart(touch: cc.Event.EventTouch) {
        this.isMoved = false;
        this.lastPoint = touch.getLocation();
        super.touchStart(touch);
        this.touches = touch.getTouches()
        if (touch.getTouches().length == 2) {
            this.zoomIn(touch.getTouches());
        }
        if (this.touchCount > 1) {
            return;
        }
    }
    touchMove(touch: cc.Event.EventTouch) {
        if (this.lastPoint && this.lastPoint.sub(touch.getLocation()).mag() > 30) {
            this.isMoved = true;
        }
        super.touchMove(touch);
        this.touches = touch.getTouches()
        if (touch.getTouches().length == 2) {
            this.zoomIn(touch.getTouches());
        }
        if (this.touchCount > 1) {
            return;
        }
        // console.log('UITouchScript touchMove', this.touchCount);
        let cameraComp = CameraController.instance;
        // let destPos = cameraComp.cameraDest;
        let destPos = cc.v2();
        if (cameraComp && cameraComp.node && cameraComp.node.isValid) {
            if (this.horizontal) {
                destPos.x = cameraComp.cameraDest.x - touch.getDelta().x * 1.5;
            }
            if (this.vertical) {
                destPos.y = cameraComp.cameraDest.y - touch.getDelta().y * 1.5;
            }
            this.setCameraDest(destPos);
        }
    }
    touchOver(touch) {
        super.touchOver(touch);
        this.doubleFingerDist = null;
        this.lastDoubleFingerDist = null;
        this.touches = [];
        if (this.touchCount > 1) {
            return;
        }
    }
    registerEvent() {
        super.registerEvent();
        this.node['_touchListener'].setSwallowTouches(false);
    }

    setCameraDest(destPos: cc.Vec2) {
        let cameraComp = CameraController.instance;
        // let destPos = v2();
        let limitRect = cameraComp.limitRect;
        if (limitRect) {
            // let zoomRatio = 1;
            let zoomRatio = cameraComp.cameraCmpt.zoomRatio;
            let wpos = cameraComp.node.parent.convertToWorldSpaceAR(destPos);
            let rect = new cc.Rect(
                wpos.x - cc.view.getVisibleSize().width / 2 / zoomRatio,
                wpos.y - cc.view.getVisibleSize().height / 2 / zoomRatio,
                cc.view.getVisibleSize().width / zoomRatio,
                cc.view.getVisibleSize().height / zoomRatio,
            )

            if (rect.containsRect(limitRect)) {
                return;
            }
            if (rect.x < limitRect.x) {
                destPos.x += limitRect.x - rect.x;
            }
            if (rect.x + rect.width > limitRect.x + limitRect.width) {
                destPos.x += (limitRect.x + limitRect.width) - (rect.x + rect.width);
            }
            if (rect.y < limitRect.y) {
                destPos.y += limitRect.y - rect.y;
            }
            if (rect.y + rect.height > limitRect.y + limitRect.height) {
                destPos.y += (limitRect.y + limitRect.height) - (rect.y + rect.height);
            }
        }
        cameraComp.setFollow(destPos, 10);
    }

}
